package com.work.oauth.controller;

import com.work.device.feign.UserFeign;
import com.work.device.pojo.UserInfo;
import com.work.entity.Result;
import com.work.entity.StatusCode;
import com.work.oauth.service.AuthService;
import com.work.oauth.util.AuthToken;
import com.work.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserFeign userFeign;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @PostMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response, @RequestParam(defaultValue = "654321", required = false) String upPassword) {

        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不存在或者错误");
        }

        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("用户名不存在或者密码错误");
        }

        //查询用户基本信息
        UserInfo userInfo = userFeign.findUserInfo(username);
        if (userInfo == null) {
            throw new RuntimeException("用户不存在");
        }

        //用户状态异常,0:账户锁定、账户异常
        if (userInfo != null && userInfo.getStatus().equals("0")) {
            throw new RuntimeException("用户状态异常");
        }

        //用户初始密码修改
        if (userInfo.getStatus() != "1" && password.equals("123456")) {

            userFeign.updataUser(username, upPassword);

            throw new RuntimeException("请修改初始密码后登录");
        }

        AuthToken authToken = authService.login(username, password, clientId, clientSecret);


        this.saveJtiToCookie(authToken.getJti(), response);

        return new Result(true, StatusCode.FIND_Ok, "登录成功");
    }

    private void saveJtiToCookie(String jti, HttpServletResponse response) {
        //存储jti到cookie中
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);
    }

    //访问登录页面
  /*  @RequestMapping("/toLogin")
    public String toLogin(@RequestParam(name = "FROM", defaultValue = "", required = false) String from, Model model) {
        model.addAttribute("from", from);
        return "login";
    }*/


}
